Import Necessary Modules¶

In [1]:
from pathlib import Path

from ipyniivue import download_dataset

BASE_API_URL = "https://niivue.com/demos/images/"
DATA_FOLDER = Path("images")

# Download data for example
download_dataset(
    BASE_API_URL,
    dest_folder=DATA_FOLDER,
    files=[
        "inia19-t1-brain.nii.gz",
        "inia19-NeuroMaps.nii.gz",
    ],
)
inia19-t1-brain.nii.gz already exists.
inia19-NeuroMaps.nii.gz already exists.
Dataset downloaded successfully to images.
In [2]:
import ipywidgets as widgets
from IPython.display import display

from ipyniivue import DragMode, NiiVue, ShowRender

# Setup NiiVue Instance
nv = NiiVue(
    back_color=(0.5, 0.5, 0.5, 1),
    show_3d_crosshair=True,
    drag_mode=DragMode.PAN,
    yoke_3d_to_2d_zoom=True,
    multiplanar_show_render=ShowRender.ALWAYS,
)

nv.load_volumes(
    [
        {"path": DATA_FOLDER / "inia19-t1-brain.nii.gz"},
        {"path": DATA_FOLDER / "inia19-NeuroMaps.nii.gz", "opacity": 0.5},
    ]
)

nv.volumes[1].set_colormap_label_from_url(
    "https://niivue.com/demos/images/inia19-NeuroMaps.json"
)

nv.volumes[1].opacity = 0.188
nv.set_atlas_outline(1.0)

# Create interactive widgets

# Slider for opacity
opacity_slider = widgets.IntSlider(
    min=1,
    max=255,
    value=48,
    description="Opacity",
    continuous_update=True,
)

# Slider for outline
outline_slider = widgets.IntSlider(
    min=0,
    max=255,
    value=255,
    description="Outline",
    continuous_update=True,
)

location_label = widgets.HTML(" ")

# Define callbacks


def on_opacity_change(change):
    """Update the opacity of the atlas volume."""
    nv.volumes[1].opacity = change["new"] / 255


def on_outline_change(change):
    """Update the outline thickness of the atlas."""
    nv.set_atlas_outline(change["new"] / 255)


def handle_location_change(location):
    """Update the location label with current coordinates."""
    location_label.value = location["string"]


# Setup observers

opacity_slider.observe(on_opacity_change, names="value")
outline_slider.observe(on_outline_change, names="value")

nv.on_location_change(handle_location_change)

on_opacity_change({"new": opacity_slider.value})
on_outline_change({"new": outline_slider.value})

# Display all

controls = widgets.HBox([opacity_slider, outline_slider])

display(
    widgets.VBox(
        [
            controls,
            nv,
            location_label,
        ]
    )
)